class Admin::ArticlesController < Admin::BaseController

  verify :method => :post, :only => [:create, :update, :destroy],
         :redirect_to => {:action => 'index'}

  def index
    @articles = Article.paginate_all_by_lough_id(current_user.lough.id,
                                                :page => params[:page],
                                                :order => 'published_at DESC')
    @action_title = 'Articles'
  end
  
  before_filter :use_tinymce_plugin, :only => [:new, :edit]

  def new
    @article = Article.new
    @action_title = 'Post new article'
  end
  
  def create
    @article = current_user.with_options(default_article_options) do |user|
      user.add_article(params[:article].symbolize_keys)
    end
    
    if request.post? && @article.save
      flash[:notice] = 'Success: Post was created.'
      redirect_to :action => 'index'
    else
      render :action => 'new'
    end
  end

  def edit
  	@action_title = 'Edit article'
    @article = Article.find_by_id(params[:id])
    
    if @article.nil?
      redirect_to :action => 'index'
    end
  end
  
  def update
    @article = Article.find_by_id(params[:id])
    if @article.update_attributes(params[:article].symbolize_keys)
      flash[:notice] = 'Success: Post was updated.'
      redirect_to :action => 'index'
    else
      render :action => 'edit'
    end
  end
  
  def destroy
  	@article = Article.find_by_id(params[:id])
  	
  	if @article
      @article.destroy
      flash[:notice] = 'Success: Post was destroyed.'
    end
    
    redirect_to :action => 'index'
  end
  
  protected 
  
  def default_article_options
    return {:lough => current_lough, :published_at => Time.now, :published => true}
  end
  
  def use_tinymce_plugin
  	@tinymce_used = true  	
  end
    
end
